package elems;

import common.ParseException;
import common.Strings;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Anchor extends ClassElem{
    private String name;
    private String comment;
    private String params;

    private Anchor(Clazz parent, String name, String comment, String params) {
        super(parent);
        this.name = name;
        this.comment = comment;
        this.params = params;
    }

    public void print(int shift){
        System.out.println(Strings.getSpaceShift(shift) + "@@" + name + "(какие-то параметры: "+params+") /* [ANCHOR CALL] " + comment + "*/");
    }

    public static boolean is(int lineNum, String text) throws ParseException {
        String tText = Strings.split(lineNum, Strings.trimAndDelDoubleSpace(text), "//", true, true).get(0).trim();

        Pattern pattern = Pattern.compile("^@@[A-Za-z0-9_]+ *(|\\(.*\\))$");
        Matcher matcher = pattern.matcher(tText);

        return matcher.find();
    }

    public static Anchor get(Clazz parent, int lineNum, String text) throws ParseException {
        if(!is(lineNum,text))
            return null;
        ArrayList<String> ttt = Strings.split(lineNum, Strings.trimAndDelDoubleSpace(text), "//", true, true);
        String tText = Strings.replaceAll(ttt.get(0), " ", "");
        String tComment = (ttt.size() > 1) ? ttt.get(1).trim() : "";

        Pattern pattern = Pattern.compile("^@@[A-Za-z0-9_]+");
        Matcher matcher = pattern.matcher(tText);
        if (matcher.find()) {
            pattern = Pattern.compile("^@@[A-Za-z0-9_]+");
            matcher = pattern.matcher(tText);
            matcher.find();
            String name = matcher.group().substring(2);
            pattern = Pattern.compile("\\(.*\\)");
            matcher = pattern.matcher(tText);
            String params="";
            if (matcher.find()) {
                params = matcher.group();
                params = params.substring(1, params.length() - 1);
            }
            return new Anchor(parent, name, tComment, params);
        }
        return null;
    }

}
